<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends Admin_Controller {
    
    public $folder = 'users/';
	
	public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
		$this->load->model('menu_model');
		$this->load->library('form_validation');
    }
    
    // ------------------------------------------------------------------------
	
	public function index()
	{
		redirect('users/all');
	}
	
	// ------------------------------------------------------------------------
    
    public function all()
    {
        $config = array(
            'base_url'      => site_url('admin/users/all/page'),
            'total_rows'    => $this->user_model->count_users(),
            'per_page'      => 30,
            'uri_segment'   => 5
        );
        
        $data = array(
            'title'     => 'Users',
            'content'   => $this->folder . 'users',
            'active'    => 'users',
            'users'     => !$config['total_rows'] ? FALSE : $this->user_model->list_users($config['per_page'], $this->uri->segment(5))
        );
        
        $this->load->library('pagination', $config);
        $this->load->view($this->tpl_admin, $data);
    }
    
    // ------------------------------------------------------------------------
	
	public function create_user()
	{
		if ($this->input->is_ajax_request())
		{
			$this->form_validation->set_rules('firstname', '<strong>First Name</strong>', 'required|trim|alpha_space|min_length[2]');
			$this->form_validation->set_rules('lastname', '<strong>Last Name</strong>', 'required|trim|alpha_space|min_length[2]');
			$this->form_validation->set_rules('email', '<strong>Email</strong>', 'required|trim|valid_email|unique[users.email]');
			
			if ($this->input->post('with_password'))
			{
				$this->form_validation->set_rules('password', '<strong>Password</strong>', 'required|trim|min_length[6]');
			}
			
			$this->form_validation->set_rules('roles', '<strong>Role</strong>', 'required|integer|exists[roles.role_id]');
			$this->form_validation->set_rules('websites', '<strong>Websites</strong>', 'required|exists[websites.site_code]');
			
			if ($this->form_validation->run())
			{
				$post = array(
					'email'			=> $this->input->post('email', TRUE),
					'password'		=> $this->input->post('with_password') ? $this->input->post('password', TRUE) : uniqid()
				);
				
				$others = array(
					'firstname'		=> $this->input->post('firstname', TRUE),
					'lastname'		=> $this->input->post('lastname', TRUE),
					'role_id'		=> $this->input->post('roles', TRUE)
				);
				
				// create user
				$query = $this->auth_model->register($post, $others);
				
				// create user websites
				$this->website_model->create_user_websites($this->input->post('websites', TRUE), $query['user_id']);
				
				//log
				$this->log_action('c', 'User ID #' . $query['user_id']);
				$this->response(TRUE, $post['password']);
			}
			
			// false
			$this->response(FALSE, 'error', validation_errors());
		}
		
		// load view instead
		$data = array(
			'title'		=> 'Create User',
			'content'	=> $this->folder . 'create_user',
			'active'	=> 'users',
			'roles'		=> $this->auth_model->list_roles(),
			'websites'	=> $this->website_model->list_websites()
		);
		
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function edit_user($user_id = '')
	{
		if ($user_id)
		{
			$user = $this->user_model->get_user($user_id);
			
			if ($user)
			{
				if ($this->input->is_ajax_request())
				{
					$this->form_validation->set_rules('firstname', '<strong>First Name</strong>', 'required|trim|alpha_space|min_length[2]');
					$this->form_validation->set_rules('lastname', '<strong>Last Name</strong>', 'required|trim|alpha_space|min_length[2]');
					$this->form_validation->set_rules('roles', '<strong>Role</strong>', 'required|integer|exists[roles.role_id]');
					$this->form_validation->set_rules('websites', '<strong>Websites</strong>', 'required|exists[websites.site_code]');
					
					if ($this->form_validation->run())
					{
						$post = array(
							'firstname'		=> $this->input->post('firstname', TRUE),
							'lastname'		=> $this->input->post('lastname', TRUE),
							'role_id'		=> $this->input->post('roles', TRUE)
						);
						
						// update user and websites
						$this->user_model->update_user($post, $user['user_id']);
						$this->website_model->update_user_websites($this->input->post('websites', TRUE), $user['user_id']);
						
						// log action
						$this->log_action('u', 'User ID #'.$user_id);
						$this->response(TRUE, 'redirect', '<p><strong>User</strong> successfully updated.</p>', site_url('users'));
					}
					
					// false
					$this->response(FALSE, 'error', validation_errors());
				}
				
				// show view
				$data = array(
					'title'			=> 'Edit User',
					'content'		=> $this->folder . 'edit_user',
					'active'		=> 'users',
					'user'			=> $user,
					'roles'			=> $this->auth_model->list_roles(),
					'websites'		=> $this->website_model->list_websites()
				);
				
				return $this->load->view($this->tpl, $data);
			}
		}
		
		show_404();
	}
	
	// ------------------------------------------------------------------------
    
    public function delete_user($user_id = '')
    {
        if ($this->input->is_ajax_request())
        {
            if ($user_id)
            {
                $this->user_model->delete_user($user_id);                
                
				$this->log_action('d', "User ID #{$user_id}");
				$this->response(TRUE);
            }
        }
        
        show_404();
    }
    
    // ------------------------------------------------------------------------
	
	public function permissions()
	{
		$config = array(
			'base_url'		=> site_url('users/permissions'),
			'total_rows'	=> $this->auth_model->count_permissions(),
			'per_page'		=> 30,
			'uri_segment'	=> 3
		);
		
		$data = array(
			'title'			=> 'Permissions',
			'content'		=> $this->folder . 'permissions',
			'active'		=> 'users',
			'permissions'	=> !$config['total_rows'] ? FALSE : $this->auth_model->list_permissions($config['per_page'], $this->uri->segment($config['uri_segment']), 'permission_url')
		);
		
		$this->load->library('pagination', $config);
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function create_permission()
	{
		if ($this->input->is_ajax_request())
		{
			$this->form_validation->set_rules('permission_name', '<strong>Name</strong>', 'required|trim|ucwords');
			$this->form_validation->set_rules('permission_url', '<strong>URL</strong>', 'required|trim|strtolower|unique[permissions.permission_url]');
			$this->form_validation->set_rules('parent', '<strong>Parent</strong>', 'exists[permissions.permission_id]');
			
			if ($this->form_validation->run())
			{
				$post = array(
					'permission_name'		=> $this->input->post('permission_name', TRUE),
					'permission_url'		=> $this->input->post('permission_url', TRUE),
					'parent_permission'		=> $this->input->post('parent', TRUE)
				);
				
				$query = $this->auth_model->create_permission($post);
				
				// log action
				$this->log_action('c', 'Permission ID #' . $query['permission_id']);
				$this->response(TRUE, 'redirect', '<p>New <strong>Permission</strong> successfully created.</p>', site_url('users/permissions'));
			}
			
			$this->response(FALSE, 'error', validation_errors());
		}
		
		$data = array(
			'title'		=> 'Create Permission',
			'content'	=> $this->folder . 'create_permission',
			'active'	=> 'users',
			'parents'	=> $this->auth_model->list_permissions(NULL, '', 'permission_name', '*', array('parent_permission' => 0))
		);
		
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function edit_permission($permission_id = '')
	{
		if ($permission_id)
		{
			$permission = $this->auth_model->get_permission($permission_id);
			
			if ($permission)
			{
				if ($this->input->is_ajax_request())
				{
					$this->form_validation->set_rules('permission_name', '<strong>Name</strong>', 'required|trim|ucwords');
					$this->form_validation->set_rules('permission_url', '<strong>URL</strong>', "required|trim|strtolower|unique[permissions.permission_url.permission_id.{$permission_id}]");
					$this->form_validation->set_rules('parent', '<strong>Parent</strong>', 'exists[permissions.permission_id]');
					
					if ($this->form_validation->run())
					{
						$post = array(
							'permission_name'		=> $this->input->post('permission_name', TRUE),
							'permission_url'		=> $this->input->post('permission_url', TRUE),
							'parent_permission'		=> $this->input->post('parent', TRUE)
						);
						
						$this->auth_model->update_permission($post, $permission['permission_id']);
						
						// log action
						$this->log_action('u', 'Permission ID #' . $permission_id);
						$this->response(TRUE, 'redirect', '<p><strong>Permission</strong> successfully updated.</p>', site_url('users/permissions'));
					}
					
					$this->response(FALSE, 'errors', validation_errors());
				}
				
				$data = array(
					'title'			=> 'Edit Permission',
					'content'		=> $this->folder . 'edit_permission',
					'active'		=> 'users',
					'permission'	=> $permission,
					'parents'		=> $this->auth_model->list_permissions(NULL, '', 'permission_name', '*', array('parent_permission' => 0))
				);
				
				return $this->load->view($this->tpl, $data);
			}
		}
		
		show_404();
	}
	
	// ------------------------------------------------------------------------
	
	public function delete_permission($permission_id = '')
	{
		if ($this->input->is_ajax_request())
		{
			if ($permission_id)
			{
				$permission = $this->auth_model->get_permission($permission_id);
				
				if ($permission)
				{
					$this->auth_model->delete_permission($permission_id);
					
					// log action
					$this->log_action('d', 'Permission ID #' . $permission_id);
					$this->response(TRUE, 'custom', '<strong>Permission</strong> successfully deleted.');
				}
			}
			
			show_404();
		}
		
		show_error('Invalid header request.', 405, '405 Method Not Allowed');
	}
	
	// ------------------------------------------------------------------------
	
	public function roles()
	{
		$data = array(
			'title'			=> 'Role Access',
			'content'		=> $this->folder . 'roles',
			'active'		=> 'users',
			'roles'			=> $this->auth_model->list_roles()
		);
		
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function edit_role($role_id = '')
	{
		if ($role_id)
		{
			$role = $this->auth_model->get_role_permissions($role_id);
			
			if ($role)
			{
				if ($this->input->is_ajax_request())
				{
					$this->form_validation->set_rules('role_name', '<strong>Role Name</strong>', 'required|trim|ucwords');
					if ($role['role_id'] != 1) $this->form_validation->set_rules('permission', '<strong>Permissions</strong>', 'exists[permissions.permission_id]');
					$this->form_validation->set_rules('menus', '<strong>Menus</strong>', 'required|exists[menus.menu_id]');
					
					if ($this->form_validation->run())
					{
						$post = array(
							'role_name'		=> $this->input->post('role_name', TRUE),
							'permissions'	=> $this->input->post('permission', TRUE)
						);
						
						// save this permission
						$this->auth_model->update_role_permission($post, $role['role_id']);
						$this->menu_model->update_role_menus(array('menus' => $this->input->post('menus', TRUE)), $role['role_id']);
						
						// log action
						$this->log_action('u', 'Role ID #' . $role_id);
						$this->response(TRUE, 'redirect', '<p><strong>Role Access</strong> successfully updated.</p>', site_url('users/roles'));
					}
					
					$this->response(FALSE, 'error', validation_errors());
				}
				
				// load view
				$data = array(
					'title'			=> 'Edit Role Access',
					'content'		=> $this->folder . 'edit_role',
					'active'		=> 'users',
					'role'			=> $role,
					'permissions'	=> $this->auth_model->list_permissions(NULL, '', 'parent_permission, permission_name'),
					'menus'			=> $this->menu_model->list_role_menus($role['role_id'])
				);
				
				return $this->load->view($this->tpl, $data);
			}
		}
		
		show_404();
	}
	
	// ------------------------------------------------------------------------
	
	public function logs()
	{
		$this->load->helper('date');
		
		$config = array(
			'base_url'		=> site_url('users/logs'),
			'total_rows'	=> $this->user_model->count_logs(),
			'per_page'		=> 30,
			'uri_segment'	=> 3
		);
		
		$data = array(
			'title'			=> 'User Logs',
			'content'		=> $this->folder . 'user_logs',
			'active'		=> 'users',
			'logs'			=> !$config['total_rows'] ? FALSE : $this->user_model->list_logs($config['per_page'], $this->uri->segment($config['uri_segment']))
		);
		
		$this->load->library('pagination', $config);
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function create_menu()
	{
		if ($this->input->is_ajax_request())
		{
			if (! $this->input->post('is_divider'))
			{
				$this->form_validation->set_rules('menu_name', '<strong>Name</strong>', 'required|trim|ucwords');
				$this->form_validation->set_rules('menu_url', '<strong>URL</strong>', 'required|trim|strtolower|unique[menus.url]');
			}
			
			$this->form_validation->set_rules('parent', '<strong>Parent</strong>', 'exists[menus.menu_id]');
			
			if ($this->form_validation->run())
			{
				$post['parent_menu']	= $this->input->post('parent', TRUE);
				$post['divider'] 		= $this->input->post('is_divider', TRUE) ? $this->input->post('is_divider', TRUE) : 'n';
				
				if ($post['divider'] == 'n')
				{
					$post['name'] 	= $this->input->post('menu_name', TRUE);
					$post['url']  	= $this->input->post('menu_url', TRUE);
				}
				
				$query = $this->menu_model->create_menu($post);
				
				// log action
				$this->log_action('c', 'Menu ID #' . $query['menu_id']);
				$this->response(TRUE, 'redirect', '<p>New <strong>Menu</strong> successfully created</p>', site_url('users/menus'));
			}
			
			$this->response(FALSE, 'error', validation_errors());
		}
		
		$data = array(
			'title'			=> 'Create Menu Item',
			'content'		=> $this->folder . 'create_menu',
			'active'		=> 'users',
			'menus'			=> $this->menu_model->list_menus(NULL, NULL, 'name', array('parent_menu' => 0))
		);
		
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function menus()
	{
		$config = array(
			'base_url'		=> site_url('users/menus'),
			'total_rows'	=> $this->menu_model->count_menus(),
			'per_page'		=> 30,
			'uri_segment'	=> 3
		);
		
		$data = array(
			'title'			=> 'Menus',
			'content'		=> $this->folder . 'menus',
			'active'		=> 'users',
			'menus'			=> !$config['total_rows'] ? FALSE : $this->menu_model->list_menus($config['per_page'], $this->uri->segment($config['uri_segment']), 'url', array('divider' => 'n'))
		);
		
		$this->load->library('pagination', $config);
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function create_role()
	{
		if ($this->input->is_ajax_request())
		{
			$this->form_validation->set_rules('role_name', '<strong>Role Name</strong>', 'required|trim');
			$this->form_validation->set_rules('permission', '<strong>Permissions</strong>', 'exists[permissions.permission_id]');
			$this->form_validation->set_rules('menus', '<strong>Menus</strong>', 'required|exists[menus.menu_id]');
			
			if ($this->form_validation->run())
			{
				// save role
				$role = $this->auth_model->create_role(array('role_name' => $this->input->post('role_name', TRUE)));
				
				// save permission and menus
				$this->auth_model->create_role_permissions($role['role_id'], $this->input->post('permission', TRUE));
				$this->menu_model->create_role_menus($role['role_id'], $this->input->post('menus', TRUE));
				
				// log action
				$this->log_action('c', 'Role ID #' . $role['role_id']);
				$this->response(TRUE, 'redirect', '<p>New <strong>Role</strong> successfully created.</p>');
			}
			
			$this->response(FALSE, 'error', validation_errors());
		}
		
		$data = array(
			'title'			=> 'Create Role',
			'content'		=> $this->folder . 'create_role',
			'active'		=> 'users',
			'permissions'	=> $this->auth_model->list_permissions(NULL, '', 'parent_permission, permission_name'),
			'menus'			=> $this->menu_model->list_menus(NULL)
		);
		
		$this->load->view($this->tpl, $data);
	}
	
	// ------------------------------------------------------------------------
	
	public function edit_menu($menu_id = '')
	{
		if ($menu_id)
		{
			$menu = $this->menu_model->get_menu($menu_id);
			
			if ($menu)
			{
				if ($this->input->is_ajax_request())
				{
					$this->form_validation->set_rules('menu_name', '<strong>Name</strong>', 'required');
					$this->form_validation->set_rules('menu_url', '<strong>URL</strong>', "required|trim|strtolower|unique[menus.url.menu_id.{$menu_id}]");
					
					if ($this->form_validation->run())
					{
						$post = array(
							'name'			=> $this->input->post('menu_name', TRUE),
							'url'			=> $this->input->post('menu_url', TRUE),
							'parent_menu'	=> $this->input->post('parent', TRUE)
						);
						
						$this->menu_model->update_menu($post, $menu['menu_id']);
						
						$this->log_action('u', 'Menu ID #' . $menu_id);
						$this->response(TRUE, 'redirect', '<p><strong>Menu</strong> successfully updated.</p>', site_url('users/menus'));
					}
					
					$this->response(FALSE, 'error', validation_errors());
				}
				
				$data = array(
					'title'			=> 'Edit Menu',
					'content'		=> $this->folder . 'edit_menu',
					'active'		=> 'users',
					'menu'			=> $menu,
					'menus'			=> $this->menu_model->list_menus(NULL, NULL, 'name', array('parent_menu' => 0))
				);
				
				return $this->load->view($this->tpl, $data);
			}
		}
		
		show_404();
	}
	
	// ------------------------------------------------------------------------
	
	public function delete_menu($menu_id = '')
	{
		if ($this->input->is_ajax_request())
		{
			if ($menu_id)
			{
				$menu = $this->menu_model->get_menu($menu_id);
				
				if ($menu)
				{
					$this->menu_model->delete_menu($menu_id);
					$this->log_action('d', 'Menu ID #' . $menu_id);
					$this->response(TRUE);
				}
			}
			
			show_404();
		}
		
		show_error('Invalid header request.', 405, '405 Method Not Allowed');
	}
	
	// ------------------------------------------------------------------------
}

/* End of file users.php */
/* Location: ./application/controllers/admin/users.php */